package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.feign.user.service.UserFeignService;
import com.smart.community.feign.user.dto.UserDTO;
import com.smart.community.feign.user.dto.NormalUserCreateDTO;
import com.smart.community.region.dto.OwnerDTO;
import com.smart.community.region.dto.OwnerUpdateDTO;
import com.smart.community.region.dto.OwnerQueryDTO;
import com.smart.community.region.entity.Owner;
import com.smart.community.region.entity.OwnerHousehold;
import com.smart.community.region.mapper.OwnerHouseholdMapper;
import com.smart.community.region.mapper.OwnerMapper;
import com.smart.community.region.service.IBuildingService;
import com.smart.community.region.service.ICommunityService;
import com.smart.community.region.service.IHouseholdService;

import com.smart.community.region.service.IOwnerService;
import com.smart.community.region.service.IUnitService;
import com.smart.community.region.vo.OwnerVO;
import com.smart.community.region.vo.OwnerEditVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.smart.community.region.dto.OwnerStatisticsDTO;

import java.util.HashSet;

/**
 * 业主服务实现类
 * 
 * @author Wu.Liang
 * @since 2025-08-20
 * @version 1.0.0
 */
@Slf4j
@Service
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements IOwnerService {
    
    @Autowired
    private DataScopeFeign dataScopeFeign;
    
    @Autowired
    private OwnerHouseholdMapper ownerHouseholdMapper;
    
    @Autowired
    private IHouseholdService householdService;
    
    @Autowired
    private ICommunityService communityService;
    
    @Autowired
    private IBuildingService buildingService;
    
    @Autowired
    private IUnitService unitService;
    
    @Autowired
    private UserFeignService userFeignService;
    
    @Override
    public IPage<OwnerVO> getOwnerPage(OwnerQueryDTO queryDTO) throws Exception {
        log.info("分页查询业主列表，查询条件：{}", queryDTO);
        
        // 获取当前用户ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            log.warn("当前用户未登录，返回空列表");
            return createEmptyPage(queryDTO);
        }
        
        // 应用数据权限过滤
        Set<Long> accessibleOwnerIds = getAccessibleOwnerIds(currentUserId);
        if (accessibleOwnerIds.isEmpty()) {
            log.warn("用户无权限访问任何业主数据，返回空列表，用户ID：{}", currentUserId);
            return createEmptyPage(queryDTO);
        }
        
        // 构建查询条件
        LambdaQueryWrapper<Owner> queryWrapper = buildQueryWrapper(queryDTO);
        
        // 添加数据权限过滤条件
        queryWrapper.in(Owner::getId, accessibleOwnerIds);
        
        // 创建分页对象
        Page<Owner> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        
        // 执行分页查询
        IPage<Owner> ownerPage = this.page(page, queryWrapper);
        
        // 转换为VO
        List<OwnerVO> ownerVOList = ownerPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<OwnerVO> resultPage = new Page<>(ownerPage.getCurrent(), ownerPage.getSize(), ownerPage.getTotal());
        resultPage.setRecords(ownerVOList);
        
        log.info("分页查询业主列表成功，总记录数：{}，用户ID：{}", ownerPage.getTotal(), currentUserId);
        return resultPage;
    }
    
    @Override
    public OwnerVO getOwnerById(Long id) throws Exception {
        log.info("根据ID查询业主详情，业主ID：{}", id);
        
        if (id == null) {
            throw new BusinessException("业主ID不能为空");
        }
        
        Owner owner = this.getById(id);
        if (owner == null) {
            throw new BusinessException("业主不存在");
        }
        
        OwnerVO ownerVO = convertToVO(owner);
        log.info("根据ID查询业主详情成功，业主ID：{}", id);
        return ownerVO;
    }
    
    @Override
    public OwnerEditVO getOwnerEditById(Long id) throws Exception {
        log.info("根据ID查询业主编辑数据，业主ID：{}", id);
        
        if (id == null) {
            throw new BusinessException("业主ID不能为空");
        }
        
        Owner owner = this.getById(id);
        if (owner == null) {
            throw new BusinessException("业主不存在");
        }
        
        OwnerEditVO ownerEditVO = convertToEditVO(owner);
        log.info("根据ID查询业主编辑数据成功，业主ID：{}", id);
        return ownerEditVO;
    }
    
    @Override
    public Long createOwner(OwnerDTO dto) throws Exception {
        log.info("创建业主，业主信息：{}", dto);
        
        // 参数验证
        validateOwnerData(dto);
        
        // 检查身份证号是否已存在
        if (checkIdCardExists(dto.getIdCard(), null)) {
            throw new BusinessException("身份证号已存在");
        }
        
        // 检查手机号是否已存在
        if (StringUtils.hasText(dto.getPhone()) && checkPhoneExists(dto.getPhone(), null)) {
            throw new BusinessException("手机号已存在");
        }
        
        // 1. 首先根据身份证号查询用户，如果查到了，则填入所有对应的信息
        UserDTO existingUser = null;
        if (StringUtils.hasText(dto.getIdCard())) {
            try {
                existingUser = userFeignService.getUserByIdCard(dto.getIdCard());
                if (existingUser != null) {
                    log.info("根据身份证号找到用户，用户ID：{}，身份证号：{}", existingUser.getId(), dto.getIdCard());
                    // 填入用户信息到业主信息中
                    fillOwnerInfoFromUser(dto, existingUser);
                }
            } catch (Exception e) {
                log.warn("根据身份证号查询用户失败，身份证号：{}，错误：{}", dto.getIdCard(), e.getMessage());
            }
        }
        
        // 2. 如果身份证号查询不到用户，则根据手机号查询用户，如果查到了，也是填入所有对应的信息
        if (existingUser == null && StringUtils.hasText(dto.getPhone())) {
            try {
                existingUser = userFeignService.getUserByPhone(dto.getPhone());
                if (existingUser != null) {
                    log.info("根据手机号找到用户，用户ID：{}，手机号：{}", existingUser.getId(), dto.getPhone());
                    // 填入用户信息到业主信息中
                    fillOwnerInfoFromUser(dto, existingUser);
                }
            } catch (Exception e) {
                log.warn("根据手机号查询用户失败，手机号：{}，错误：{}", dto.getPhone(), e.getMessage());
            }
        }
        
        // 3. 如果根据手机号还是查询不到用户，那我们就需要新增用户，新增用户时填入所有对应的信息，用户名和密码则全部都使用手机号
        if (existingUser == null && StringUtils.hasText(dto.getPhone())) {
            try {
                Long newUserId = createNewUser(dto);
                if (newUserId != null) {
                    log.info("创建新用户成功，用户ID：{}，手机号：{}", newUserId, dto.getPhone());
                    existingUser = new UserDTO();
                    existingUser.setId(newUserId);
                }
            } catch (Exception e) {
                log.error("创建新用户失败，手机号：{}，错误：{}", dto.getPhone(), e.getMessage());
                throw new BusinessException("创建用户失败：" + e.getMessage());
            }
        }
        
        // 构建实体对象
        Owner owner = buildOwnerEntity(dto);
        
        // 设置默认值
        if (owner.getStatus() == null) {
            owner.setStatus(SystemStatusEnum.ENABLED.getCode());
        }
        
        // 保存业主信息
        this.save(owner);
        
        // 4. 不管是查到了用户还是新增用户，我们都需要看用户类型是不是'Owner'业主，如果是新增用户，直接设置用户类型为'Owner'，然后关联角色'Owner'（即id=6的角色）
        // 5. 如果是查询到的用户，我们则不修改他的用户类型，我们直接给他新增关联角色'Owner'（即id=6的角色）即可
        if (existingUser != null) {
            try {
                // 检查用户是否已经有业主角色
                List<String> userRoles = getUserRolesFromUserService(existingUser.getId());
                if (userRoles == null || !userRoles.contains("OWNER")) {
                    // 为用户分配业主角色（角色ID=15）
                    List<Long> roleIds = new ArrayList<>();
                    roleIds.add(15L); // 业主角色ID
                    userFeignService.assignUserRoles(existingUser.getId(), roleIds);
                    log.info("为用户分配业主角色成功，用户ID：{}", existingUser.getId());
                } else {
                    log.info("用户已有业主角色，无需重复分配，用户ID：{}", existingUser.getId());
                }
            } catch (Exception e) {
                log.error("为用户分配业主角色失败，用户ID：{}，错误：{}", existingUser.getId(), e.getMessage());
                // 不抛出异常，业主创建成功，角色分配失败不影响业主创建
            }
        }
        
        log.info("创建业主成功，业主ID：{}", owner.getId());
        return owner.getId();
    }
    
    @Override
    public void updateOwner(Long id, OwnerDTO dto) throws Exception {
        log.info("更新业主信息，业主ID：{}，业主信息：{}", id, dto);
        
        if (id == null) {
            throw new BusinessException("业主ID不能为空");
        }
        
        // 检查业主是否存在
        Owner existingOwner = this.getById(id);
        if (existingOwner == null) {
            throw new BusinessException("业主不存在");
        }
        
        // 参数验证
        validateOwnerData(dto);
        
        // 检查手机号是否已存在（排除当前业主）
        if (StringUtils.hasText(dto.getPhone()) && checkPhoneExists(dto.getPhone(), id)) {
            throw new BusinessException("手机号已存在");
        }
        
        // 构建实体对象
        Owner owner = buildOwnerEntity(dto);
        owner.setId(id);
        
        // 更新业主信息
        this.updateById(owner);
        
        log.info("更新业主信息成功，业主ID：{}", id);
    }
    
    @Override
    public void updateOwner(Long id, OwnerUpdateDTO dto) throws Exception {
        log.info("更新业主信息，业主ID：{}，业主信息：{}", id, dto);
        
        if (id == null) {
            throw new BusinessException("业主ID不能为空");
        }
        
        // 检查业主是否存在
        Owner existingOwner = this.getById(id);
        if (existingOwner == null) {
            throw new BusinessException("业主不存在");
        }
        
        // 参数验证
        validateOwnerData(dto);
        
        // 检查手机号是否已存在（排除当前业主）
        if (StringUtils.hasText(dto.getPhone()) && checkPhoneExists(dto.getPhone(), id)) {
            throw new BusinessException("手机号已存在");
        }
        
        // 构建实体对象
        Owner owner = buildOwnerEntity(dto);
        owner.setId(id);
        
        // 更新业主信息
        this.updateById(owner);
        
        log.info("更新业主信息成功，业主ID：{}", id);
    }
    
    @Override
    public void deleteOwner(Long id) throws Exception {
        log.info("删除业主，业主ID：{}", id);
        
        if (id == null) {
            throw new BusinessException("业主ID不能为空");
        }
        
        // 检查业主是否存在
        Owner owner = this.getById(id);
        if (owner == null) {
            throw new BusinessException("业主不存在");
        }
        
        // 删除业主信息（软删除）
        this.removeById(id);
        
        log.info("删除业主成功，业主ID：{}", id);
    }
    
    @Override
    public void batchDeleteOwners(List<Long> ids) throws Exception {
        log.info("批量删除业主，业主ID列表：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("业主ID列表不能为空");
        }
        
        // 批量删除业主信息（软删除）
        this.removeByIds(ids);
        
        log.info("批量删除业主成功，删除数量：{}", ids.size());
    }
    
    @Override
    public Owner getOwnerByUserId(Long userId) throws Exception {
        log.info("根据用户ID查询业主，用户ID：{}", userId);
        
        if (userId == null) {
            return null;
        }
        
        return baseMapper.selectByUserId(userId);
    }
    
    @Override
    public Owner getOwnerByIdCard(String idCard) throws Exception {
        log.info("根据身份证号查询业主，身份证号：{}", idCard);
        
        if (!StringUtils.hasText(idCard)) {
            return null;
        }
        
        return baseMapper.selectByIdCard(idCard);
    }
    
    @Override
    public Owner getOwnerByPhone(String phone) throws Exception {
        log.info("根据手机号查询业主，手机号：{}", phone);
        
        if (!StringUtils.hasText(phone)) {
            return null;
        }
        
        return baseMapper.selectByPhone(phone);
    }
    
    @Override
    public List<Owner> getOwnersByHouseholdId(Long householdId) throws Exception {
        log.info("根据房户ID查询关联的业主列表，房户ID：{}", householdId);
        
        if (householdId == null) {
            return Collections.emptyList();
        }
        
        return baseMapper.selectByHouseholdId(householdId);
    }
    
    @Override
    public List<Owner> getOwnersByCommunityId(Long communityId) throws Exception {
        log.info("根据社区ID查询业主列表，社区ID：{}", communityId);
        
        if (communityId == null) {
            return Collections.emptyList();
        }
        
        return baseMapper.selectByCommunityId(communityId);
    }
    
    @Override
    public List<Owner> getOwnersByBuildingId(Long buildingId) throws Exception {
        log.info("根据楼栋ID查询业主列表，楼栋ID：{}", buildingId);
        
        if (buildingId == null) {
            return Collections.emptyList();
        }
        
        return baseMapper.selectByBuildingId(buildingId);
    }
    
    @Override
    public List<Owner> getOwnersByUnitId(Long unitId) throws Exception {
        log.info("根据单元ID查询业主列表，单元ID：{}", unitId);
        
        if (unitId == null) {
            return Collections.emptyList();
        }
        
        return baseMapper.selectByUnitId(unitId);
    }
    
    @Override
    public boolean checkIdCardExists(String idCard, Long excludeId) throws Exception {
        if (!StringUtils.hasText(idCard)) {
            return false;
        }
        
        Owner existingOwner = baseMapper.selectByIdCard(idCard);
        if (existingOwner == null) {
            return false;
        }
        
        return !existingOwner.getId().equals(excludeId);
    }
    
    @Override
    public boolean checkPhoneExists(String phone, Long excludeId) throws Exception {
        if (!StringUtils.hasText(phone)) {
            return false;
        }
        
        Owner existingOwner = baseMapper.selectByPhone(phone);
        if (existingOwner == null) {
            return false;
        }
        
        return !existingOwner.getId().equals(excludeId);
    }
    
    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Owner> buildQueryWrapper(OwnerQueryDTO queryDTO) {
        LambdaQueryWrapper<Owner> queryWrapper = new LambdaQueryWrapper<>();
        
        // 基础条件
        queryWrapper.eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode());
        
        // 业主姓名
        if (StringUtils.hasText(queryDTO.getOwnerName())) {
            queryWrapper.like(Owner::getOwnerName, queryDTO.getOwnerName());
        }
        
        // 身份证号
        if (StringUtils.hasText(queryDTO.getIdCard())) {
            queryWrapper.like(Owner::getIdCard, queryDTO.getIdCard());
        }
        
        // 联系电话
        if (StringUtils.hasText(queryDTO.getPhone())) {
            queryWrapper.like(Owner::getPhone, queryDTO.getPhone());
        }
        
        // 邮箱地址
        if (StringUtils.hasText(queryDTO.getEmail())) {
            queryWrapper.like(Owner::getEmail, queryDTO.getEmail());
        }
        
        // 性别
        if (queryDTO.getGender() != null) {
            queryWrapper.eq(Owner::getGender, queryDTO.getGender());
        }
        
        // 职业
        if (StringUtils.hasText(queryDTO.getOccupation())) {
            queryWrapper.like(Owner::getOccupation, queryDTO.getOccupation());
        }
        
        // 工作单位
        if (StringUtils.hasText(queryDTO.getCompany())) {
            queryWrapper.like(Owner::getCompany, queryDTO.getCompany());
        }
        
        // 状态
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Owner::getStatus, queryDTO.getStatus());
        }
        
        // 关键词搜索
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Owner::getOwnerName, queryDTO.getKeyword())
                    .or()
                    .like(Owner::getIdCard, queryDTO.getKeyword())
                    .or()
                    .like(Owner::getPhone, queryDTO.getKeyword())
                    .or()
                    .like(Owner::getEmail, queryDTO.getKeyword())
            );
        }
        
        // 排序
        queryWrapper.orderByDesc(Owner::getCreateTime);
        
        return queryWrapper;
    }
    
    /**
     * 转换为VO对象
     */
    private OwnerVO convertToVO(Owner owner) {
        if (owner == null) {
            return null;
        }
        
        OwnerVO ownerVO = new OwnerVO();
        BeanUtils.copyProperties(owner, ownerVO);
        
        // 设置关联房户数量（这里需要根据实际业务逻辑实现）
        ownerVO.setHouseholdCount(0);
        
        return ownerVO;
    }
    
    /**
     * 转换为EditVO对象
     */
    private OwnerEditVO convertToEditVO(Owner owner) {
        if (owner == null) {
            return null;
        }
        
        OwnerEditVO ownerEditVO = new OwnerEditVO();
        BeanUtils.copyProperties(owner, ownerEditVO);
        
        return ownerEditVO;
    }
    
    /**
     * 验证业主数据
     * 
     * @param dto 业主数据
     * @throws BusinessException 业务异常
     */
    private void validateOwnerData(OwnerDTO dto) throws BusinessException {
        if (dto == null) {
            throw new BusinessException("业主信息不能为空");
        }
        
        if (!StringUtils.hasText(dto.getOwnerName())) {
            throw new BusinessException("业主姓名不能为空");
        }
        
        if (!StringUtils.hasText(dto.getIdCard())) {
            throw new BusinessException("身份证号不能为空");
        }
        
        // 验证身份证号格式
        if (!isValidIdCard(dto.getIdCard())) {
            throw new BusinessException("身份证号格式不正确");
        }
    }
    
    /**
     * 验证业主更新数据
     * 
     * @param dto 业主更新数据
     * @throws BusinessException 业务异常
     */
    private void validateOwnerData(OwnerUpdateDTO dto) throws BusinessException {
        if (dto == null) {
            throw new BusinessException("业主信息不能为空");
        }
        
        if (!StringUtils.hasText(dto.getOwnerName())) {
            throw new BusinessException("业主姓名不能为空");
        }
    }
    
    /**
     * 构建业主实体对象
     * 
     * @param dto 业主DTO
     * @return 业主实体
     */
    private Owner buildOwnerEntity(OwnerDTO dto) {
        Owner owner = new Owner();
        BeanUtils.copyProperties(dto, owner);
        
        // 设置默认状态
        owner.setStatus(SystemStatusEnum.ENABLED.getCode());
        owner.setOwnerStatus(1); // 已激活
        
        // 设置创建和更新信息
        Long userId = SecurityUtils.getCurrentUserId();
        owner.setCreateBy(userId);
        owner.setUpdateBy(userId);
        owner.setCreateTime(LocalDateTime.now());
        owner.setUpdateTime(LocalDateTime.now());
        
        return owner;
    }
    
    /**
     * 构建业主实体对象（更新用）
     * 
     * @param dto 业主更新DTO
     * @return 业主实体
     */
    private Owner buildOwnerEntity(OwnerUpdateDTO dto) {
        Owner owner = new Owner();
        BeanUtils.copyProperties(dto, owner);
        
        // 设置更新信息
        Long userId = SecurityUtils.getCurrentUserId();
        owner.setUpdateBy(userId);
        owner.setUpdateTime(LocalDateTime.now());
        
        return owner;
    }
    
    /**
     * 验证身份证号格式
     * 
     * @param idCard 身份证号
     * @return 是否有效
     */
    private boolean isValidIdCard(String idCard) {
        if (!StringUtils.hasText(idCard)) {
            return false;
        }
        
        // 身份证号格式验证正则表达式
        String pattern = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
        return idCard.matches(pattern);
    }
    
    @Override
    public OwnerStatisticsDTO getOwnerStatistics() throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        
        try {
            // 1. 检查超级管理员权限
            Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
            
            if (isSuperAdmin) {
                // 超级管理员查看全部数据
                return getStatisticsForSuperAdmin();
            } else {
                // 物业公司管理员：获取所有社区 -> 获取所有楼栋 -> 获取所有单元 -> 获取所有房户 -> 根据这些房户查询业务和房户关联表，筛选业主ID
                return getStatisticsWithPermission(currentUserId);
            }
            
        } catch (Exception e) {
            log.error("获取业主统计信息失败，用户ID：{}", currentUserId, e);
            // 返回默认统计信息，确保系统稳定性
            return getDefaultStatistics();
        }
    }
    
    /**
     * 超级管理员统计信息
     */
    private OwnerStatisticsDTO getStatisticsForSuperAdmin() throws Exception {
        log.info("超级管理员获取业主统计信息");
        
        // 总业主数
        LambdaQueryWrapper<Owner> totalWrapper = new LambdaQueryWrapper<>();
        totalWrapper.eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode());
        long totalCount = this.count(totalWrapper);
        
        // 活跃业主数（启用状态）
        LambdaQueryWrapper<Owner> activeWrapper = new LambdaQueryWrapper<>();
        activeWrapper.eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode())
                    .eq(Owner::getStatus, SystemStatusEnum.ENABLED.getCode());
        long activeCount = this.count(activeWrapper);
        
        // 关联房产数（通过业主房户关联表统计）
        long propertyCount = getPropertyCountForSuperAdmin();
        
        // 房产证数（通过业主房户关联表统计有房产证的记录）
        long certificateCount = getCertificateCountForSuperAdmin();
        
        OwnerStatisticsDTO statistics = new OwnerStatisticsDTO();
        statistics.setTotalCount(totalCount);
        statistics.setActiveCount(activeCount);
        statistics.setPropertyCount(propertyCount);
        statistics.setCertificateCount(certificateCount);
        
        log.info("超级管理员统计信息：总业主数={}，活跃业主数={}，关联房产数={}，房产证数={}", 
                totalCount, activeCount, propertyCount, certificateCount);
        
        return statistics;
    }
    
    /**
     * 普通用户权限范围内统计信息
     */
    private OwnerStatisticsDTO getStatisticsWithPermission(Long userId) throws Exception {
        log.info("普通用户获取业主统计信息，用户ID：{}", userId);
        
        // 1. 获取用户数据权限范围
        List<Long> communityIds = dataScopeFeign.getUserCommunityIds(userId);
        if (communityIds.isEmpty()) {
            log.info("用户{}无权限访问任何社区数据，返回默认统计", userId);
            return getDefaultStatistics();
        }
        
        // 2. 根据社区ID获取房户ID集合
        Set<Long> householdIds = getHouseholdIdsByCommunityIds(communityIds);
        if (householdIds.isEmpty()) {
            log.info("用户{}权限范围内无房户数据，返回默认统计", userId);
            return getDefaultStatistics();
        }
        
        // 3. 根据房户ID获取业主ID集合
        Set<Long> ownerIds = getOwnerIdsByHouseholdIds(new ArrayList<>(householdIds));
        if (ownerIds.isEmpty()) {
            log.info("用户{}权限范围内无业主数据，返回默认统计", userId);
            return getDefaultStatistics();
        }
        
        // 4. 统计权限范围内的业主数据
        long totalCount = getOwnerCountByIds(ownerIds);
        long activeCount = getActiveOwnerCountByIds(ownerIds);
        long propertyCount = getPropertyCountByHouseholdIds(new HashSet<>(householdIds));
        long certificateCount = getCertificateCountByHouseholdIds(new HashSet<>(householdIds));
        
        OwnerStatisticsDTO statistics = new OwnerStatisticsDTO();
        statistics.setTotalCount(totalCount);
        statistics.setActiveCount(activeCount);
        statistics.setPropertyCount(propertyCount);
        statistics.setCertificateCount(certificateCount);
        
        log.info("用户{}权限范围内统计信息：总业主数={}，活跃业主数={}，关联房产数={}，房产证数={}", 
                userId, totalCount, activeCount, propertyCount, certificateCount);
        
        return statistics;
    }
    
    /**
     * 获取默认统计信息
     */
    private OwnerStatisticsDTO getDefaultStatistics() {
        OwnerStatisticsDTO statistics = new OwnerStatisticsDTO();
        statistics.setTotalCount(0L);
        statistics.setActiveCount(0L);
        statistics.setPropertyCount(0L);
        statistics.setCertificateCount(0L);
        return statistics;
    }
    
    /**
     * 超级管理员获取关联房产数
     */
    private long getPropertyCountForSuperAdmin() throws Exception {
        LambdaQueryWrapper<OwnerHousehold> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OwnerHousehold::getStatus, SystemStatusEnum.ENABLED.getCode());
        return ownerHouseholdMapper.selectCount(wrapper);
    }
    
    /**
     * 超级管理员获取房产证数
     */
    private long getCertificateCountForSuperAdmin() throws Exception {
        LambdaQueryWrapper<OwnerHousehold> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OwnerHousehold::getStatus, SystemStatusEnum.ENABLED.getCode())
               .isNotNull(OwnerHousehold::getCertificateNumber)
               .ne(OwnerHousehold::getCertificateNumber, "");
        return ownerHouseholdMapper.selectCount(wrapper);
    }
    
    /**
     * 根据社区ID集合获取房户ID集合
     */
    private Set<Long> getHouseholdIdsByCommunityIds(List<Long> communityIds) throws Exception {
        if (communityIds == null || communityIds.isEmpty()) {
            return Collections.emptySet();
        }
        
        try {
            // 调用房户服务获取房户ID集合
            List<Long> householdIds = householdService.getHouseholdIdsByCommunityIds(communityIds);
            
            if (householdIds == null || householdIds.isEmpty()) {
                log.info("房户服务返回空房户ID列表，社区数量：{}", communityIds.size());
                return Collections.emptySet();
            }
            
            log.info("通过房户服务获取房户ID集合成功，社区数量：{}，房户数量：{}", communityIds.size(), householdIds.size());
            return new HashSet<>(householdIds);
            
        } catch (Exception e) {
            log.error("调用房户服务获取房户ID集合失败，社区IDs：{}", communityIds, e);
            // 返回空集合，确保系统稳定性
            return Collections.emptySet();
        }
    }
    
    /**
     * 获取用户可访问的业主ID集合
     * 按照数据权限层级：物业公司 → 社区 → 楼栋 → 单元 → 房户 → 业主
     * 
     * @param userId 用户ID
     * @return 可访问的业主ID集合
     */
    private Set<Long> getAccessibleOwnerIds(Long userId) throws Exception {
        log.info("获取用户可访问的业主ID集合，用户ID：{}", userId);
        
        try {
            // 第1步：检查用户是否为超级管理员
            boolean isSuperAdmin = checkIsSuperAdmin(userId);
            if (isSuperAdmin) {
                log.info("超级管理员用户，返回所有业主ID，用户ID：{}", userId);
                return getAllOwnerIds();
            }
            
            // 第2步：检查用户是否有关联物业公司
            boolean hasPropertyCompany = checkUserHasPropertyCompany(userId);
            if (!hasPropertyCompany) {
                log.warn("用户未关联物业公司，返回空业主ID集合，用户ID：{}", userId);
                return Collections.emptySet();
            }
            
            // 第3步：获取用户可访问的房户ID集合
            List<Long> accessibleHouseholdIds = getUserAccessibleHouseholdIds(userId);
            if (accessibleHouseholdIds.isEmpty()) {
                log.warn("用户无权限访问任何房户，返回空业主ID集合，用户ID：{}", userId);
                return Collections.emptySet();
            }
            
            // 第4步：根据房户ID集合获取业主ID集合
            Set<Long> ownerIds = getOwnerIdsByHouseholdIds(accessibleHouseholdIds);
            
            log.info("获取用户可访问的业主ID集合完成，用户ID：{}，房户数量：{}，业主数量：{}", 
                    userId, accessibleHouseholdIds.size(), ownerIds.size());
            
            return ownerIds;
            
        } catch (Exception e) {
            log.error("获取用户可访问的业主ID集合失败，用户ID：{}", userId, e);
            return Collections.emptySet();
        }
    }
    
    /**
     * 检查用户是否为超级管理员
     * 
     * @param userId 用户ID
     * @return 是否为超级管理员
     */
    private boolean checkIsSuperAdmin(Long userId) {
        try {
            // 通过DataScopeFeign检查用户是否为超级管理员
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(userId);
            return dataScopeInfo != null && dataScopeInfo.isSuperAdmin();
        } catch (Exception e) {
            log.error("检查用户是否为超级管理员失败，用户ID：{}", userId, e);
            return false;
        }
    }
    
    /**
     * 检查用户是否有关联物业公司
     * 
     * @param userId 用户ID
     * @return 是否有关联物业公司
     */
    private boolean checkUserHasPropertyCompany(Long userId) {
        try {
            // 通过DataScopeFeign检查用户是否有关联物业公司
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(userId);
            return dataScopeInfo != null && dataScopeInfo.isPropertyCompanyUser();
        } catch (Exception e) {
            log.error("检查用户是否有关联物业公司失败，用户ID：{}", userId, e);
            return false;
        }
    }
    
    /**
     * 获取用户可访问的房户ID集合
     * 按照数据权限层级：物业公司 → 社区 → 楼栋 → 单元 → 房户
     * 
     * @param userId 用户ID
     * @return 可访问的房户ID集合
     */
    private List<Long> getUserAccessibleHouseholdIds(Long userId) throws Exception {
        log.info("获取用户可访问的房户ID集合，用户ID：{}", userId);
        
        try {
            // 第1步：获取用户关联的物业公司ID
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(userId);
            if (dataScopeInfo == null || !dataScopeInfo.isPropertyCompanyUser()) {
                log.warn("用户未关联物业公司，用户ID：{}", userId);
                return Collections.emptyList();
            }
            
            List<Long> propertyCompanyIds = dataScopeInfo.getPropertyCompanyIds();
            if (propertyCompanyIds == null || propertyCompanyIds.isEmpty()) {
                log.warn("用户物业公司ID为空，用户ID：{}", userId);
                return Collections.emptyList();
            }
            
            // 第2步：获取物业公司关联的社区ID集合
            List<Long> communityIds = dataScopeInfo.getCommunityIds();
            if (communityIds == null || communityIds.isEmpty()) {
                log.warn("物业公司未关联任何社区，物业公司IDs：{}", propertyCompanyIds);
                return Collections.emptyList();
            }
            
            // 第3步：根据社区ID集合获取楼栋ID集合
            List<Long> buildingIds = buildingService.getBuildingIdsByCommunityIds(communityIds);
            if (buildingIds.isEmpty()) {
                log.warn("社区下无楼栋数据，社区IDs：{}", communityIds);
                return Collections.emptyList();
            }
            
            // 第4步：根据楼栋ID集合获取单元ID集合
            List<Long> unitIds = unitService.getUnitIdsByBuildingIds(buildingIds);
            if (unitIds.isEmpty()) {
                log.warn("楼栋下无单元数据，楼栋IDs：{}", buildingIds);
                return Collections.emptyList();
            }
            
            // 第5步：根据单元ID集合获取房户ID集合
            List<Long> householdIds = householdService.getHouseholdIdsByUnitIds(unitIds);
            
            log.info("获取用户可访问的房户ID集合完成，用户ID：{}，物业公司IDs：{}，社区数量：{}，楼栋数量：{}，单元数量：{}，房户数量：{}", 
                    userId, propertyCompanyIds, communityIds.size(), buildingIds.size(), unitIds.size(), householdIds.size());
            
            return householdIds;
            
        } catch (Exception e) {
            log.error("获取用户可访问的房户ID集合失败，用户ID：{}", userId, e);
            return Collections.emptyList();
        }
    }
    
    /**
     * 根据房户ID集合获取业主ID集合
     * 通过业主房户关联表查询业主ID
     * 
     * @param householdIds 房户ID集合
     * @return 业主ID集合
     */
    private Set<Long> getOwnerIdsByHouseholdIds(List<Long> householdIds) throws Exception {
        log.info("根据房户ID集合获取业主ID集合，房户数量：{}", householdIds != null ? householdIds.size() : 0);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                return Collections.emptySet();
            }
            
            // 查询业主房户关联表，获取业主ID
            LambdaQueryWrapper<OwnerHousehold> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(OwnerHousehold::getHouseholdId, householdIds);
            queryWrapper.eq(OwnerHousehold::getStatus, SystemStatusEnum.ENABLED.getCode());
            queryWrapper.orderByDesc(OwnerHousehold::getCreateTime);
            
            List<OwnerHousehold> ownerHouseholds = ownerHouseholdMapper.selectList(queryWrapper);
            if (ownerHouseholds.isEmpty()) {
                log.info("房户下无业主关联数据，房户IDs：{}", householdIds);
                return Collections.emptySet();
            }
            
            // 提取业主ID集合
            Set<Long> ownerIds = ownerHouseholds.stream()
                    .map(OwnerHousehold::getOwnerId)
                    .filter(ownerId -> ownerId != null)
                    .collect(Collectors.toSet());
            
            log.info("根据房户ID集合获取业主ID集合成功，房户数量：{}，业主数量：{}", householdIds.size(), ownerIds.size());
            return ownerIds;
            
        } catch (Exception e) {
            log.error("根据房户ID集合获取业主ID集合失败，房户IDs：{}", householdIds, e);
            return Collections.emptySet();
        }
    }
    
    /**
     * 获取所有业主ID（超级管理员使用）
     * 
     * @return 所有业主ID集合
     */
    private Set<Long> getAllOwnerIds() {
        try {
            LambdaQueryWrapper<Owner> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Owner::getId);
            queryWrapper.eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode());
            
            List<Owner> owners = this.list(queryWrapper);
            Set<Long> ownerIds = owners.stream()
                    .map(Owner::getId)
                    .filter(ownerId -> ownerId != null)
                    .collect(Collectors.toSet());
            
            log.info("获取所有业主ID成功，业主数量：{}", ownerIds.size());
            return ownerIds;
            
        } catch (Exception e) {
            log.error("获取所有业主ID失败", e);
            return Collections.emptySet();
        }
    }
    
    /**
     * 创建空的分页结果
     * 
     * @param queryDTO 查询条件
     * @return 空的分页结果
     */
    private IPage<OwnerVO> createEmptyPage(OwnerQueryDTO queryDTO) {
        Page<OwnerVO> emptyPage = new Page<>(queryDTO.getCurrent(), queryDTO.getSize(), 0L);
        emptyPage.setRecords(Collections.emptyList());
        return emptyPage;
    }
    
    /**
     * 根据业主ID集合统计总业主数
     */
    private long getOwnerCountByIds(Set<Long> ownerIds) throws Exception {
        if (ownerIds.isEmpty()) {
            return 0L;
        }
        
        LambdaQueryWrapper<Owner> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Owner::getId, ownerIds)
               .eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode());
        
        return this.count(wrapper);
    }
    
    /**
     * 根据业主ID集合统计活跃业主数
     */
    private long getActiveOwnerCountByIds(Set<Long> ownerIds) throws Exception {
        if (ownerIds.isEmpty()) {
            return 0L;
        }
        
        LambdaQueryWrapper<Owner> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Owner::getId, ownerIds)
               .eq(Owner::getDeleted, SystemStatusEnum.NOT_DELETED.getCode())
               .eq(Owner::getStatus, SystemStatusEnum.ENABLED.getCode());
        
        return this.count(wrapper);
    }
    
    /**
     * 根据房户ID集合统计关联房产数
     */
    private long getPropertyCountByHouseholdIds(Set<Long> householdIds) throws Exception {
        if (householdIds.isEmpty()) {
            return 0L;
        }
        
        LambdaQueryWrapper<OwnerHousehold> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OwnerHousehold::getHouseholdId, householdIds)
               .eq(OwnerHousehold::getStatus, SystemStatusEnum.ENABLED.getCode());
        
        return ownerHouseholdMapper.selectCount(wrapper);
    }
    
    /**
     * 根据房户ID集合统计房产证数
     */
    private long getCertificateCountByHouseholdIds(Set<Long> householdIds) throws Exception {
        if (householdIds.isEmpty()) {
            return 0L;
        }
        
        LambdaQueryWrapper<OwnerHousehold> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(OwnerHousehold::getHouseholdId, householdIds)
               .eq(OwnerHousehold::getStatus, SystemStatusEnum.ENABLED.getCode())
               .isNotNull(OwnerHousehold::getCertificateNumber)
               .ne(OwnerHousehold::getCertificateNumber, "");
        
        return ownerHouseholdMapper.selectCount(wrapper);
    }
    
    /**
     * 从用户信息填充业主信息
     * 
     * @param dto 业主DTO
     * @param user 用户信息
     */
    private void fillOwnerInfoFromUser(OwnerDTO dto, UserDTO user) {
        if (user == null) {
            return;
        }
        
        // 如果业主信息中没有填写，则从用户信息中获取
        if (!StringUtils.hasText(dto.getOwnerName()) && StringUtils.hasText(user.getRealName())) {
            dto.setOwnerName(user.getRealName());
        }
        
        if (!StringUtils.hasText(dto.getIdCard()) && StringUtils.hasText(user.getIdCard())) {
            dto.setIdCard(user.getIdCard());
        }
        
        if (!StringUtils.hasText(dto.getPhone()) && StringUtils.hasText(user.getPhone())) {
            dto.setPhone(user.getPhone());
        }
        
        if (!StringUtils.hasText(dto.getEmail()) && StringUtils.hasText(user.getEmail())) {
            dto.setEmail(user.getEmail());
        }
        
        if (dto.getGender() == null && user.getGender() != null) {
            dto.setGender(user.getGender());
        }
        
        // 注意：UserDTO的getBirthday()可能返回String类型，这里暂时注释掉
        // if (dto.getBirthDate() == null && user.getBirthday() != null) {
        //     try {
        //         java.sql.Date birthday = user.getBirthday();
        //         if (birthday != null) {
        //             dto.setBirthDate(birthday.toLocalDate());
        //         }
        //     } catch (Exception e) {
        //         log.warn("转换生日日期失败，用户ID：{}", user.getId(), e);
        //     }
        // }
        
        // 注意：UserDTO可能没有address字段，这里暂时注释掉
        // if (!StringUtils.hasText(dto.getAddress()) && StringUtils.hasText(user.getAddress())) {
        //     dto.setAddress(user.getAddress());
        // }
        
        log.info("从用户信息填充业主信息完成，用户ID：{}", user.getId());
    }
    
    /**
     * 创建新用户
     * 
     * @param dto 业主DTO
     * @return 新用户ID
     * @throws Exception 统一异常
     */
    private Long createNewUser(OwnerDTO dto) throws Exception {
        if (!StringUtils.hasText(dto.getPhone())) {
            throw new BusinessException("手机号不能为空，无法创建用户");
        }
        
        NormalUserCreateDTO userCreateDTO = new NormalUserCreateDTO();
        userCreateDTO.setUsername(dto.getPhone()); // 用户名使用手机号
        userCreateDTO.setPassword(dto.getPhone()); // 密码使用手机号
        userCreateDTO.setPhone(dto.getPhone());
        userCreateDTO.setRealName(dto.getOwnerName());
        userCreateDTO.setIdCard(dto.getIdCard());
        userCreateDTO.setEmail(dto.getEmail());
        userCreateDTO.setGender(dto.getGender());
        if (dto.getBirthDate() != null) {
            // 注意：NormalUserCreateDTO的setBirthday可能接受String类型
            userCreateDTO.setBirthday(dto.getBirthDate().toString());
        }
        // 注意：NormalUserCreateDTO可能没有setAddress方法，这里暂时注释掉
        // userCreateDTO.setAddress(dto.getAddress());
        userCreateDTO.setOperatorId(SecurityUtils.getCurrentUserId());
        
        Long userId = userFeignService.createNormalUser(userCreateDTO);
        log.info("创建新用户成功，用户ID：{}，手机号：{}", userId, dto.getPhone());
        return userId;
    }
    
    /**
     * 从用户服务获取用户角色列表
     * 
     * @param userId 用户ID
     * @return 用户角色列表
     */
    private List<String> getUserRolesFromUserService(Long userId) {
        try {
            // 这里需要通过Feign接口获取用户角色，但UserFeignService中没有直接获取角色列表的方法
            // 我们可以通过DataScopeFeign来获取用户的数据权限信息，从中判断用户角色
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(userId);
            if (dataScopeInfo != null && dataScopeInfo.isOwnerUser()) {
                List<String> roles = new ArrayList<>();
                roles.add("OWNER");
                return roles;
            }
            return new ArrayList<>();
        } catch (Exception e) {
            log.warn("获取用户角色失败，用户ID：{}，错误：{}", userId, e.getMessage());
            return new ArrayList<>();
        }
    }
}
